package juc.forkJoin;

import java.util.concurrent.RecursiveTask;

/**
 * @program: check-repetition
 * @description:
 * @author: hjk
 * @create: 2021-07-13 14:12
 **/
public class ForkJoinTask extends RecursiveTask<Long> {

    private int start;
    private int end;
    private long sum;

    /**
     * 构造函数
     *
     * @param start
     * @param end
     */
    public ForkJoinTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    /**
     * The main computation performed by this task.
     *
     * @return the result of the computation
     */
    @Override
    protected Long compute() {
        System.out.println("任务" + start + "=========" + end + "累加开始");
        //大于 100 个数相加切分,小于直接加
        if (end - start <= 100) {
            for (int i = start; i <= end; i++) {
                //累加
                sum += i;
            }
        } else {
            //切分为 2 块
            int middle = start + 100;
            //递归调用,切分为 2 个小任务
            ForkJoinTask taskExample1 = new ForkJoinTask(start, middle);
            ForkJoinTask taskExample2 = new ForkJoinTask(middle + 1, end);
            //执行:异步
            taskExample1.fork();
            taskExample2.fork();
            //同步阻塞获取执行结果
            sum = taskExample1.join() + taskExample2.join();
        }
        //加完返回
        return sum;
    }
}
